package com.kum.netty.handler.impl;

import com.alibaba.fastjson.JSON;
import com.kum.api.RemoteChatMsgService;
import com.kum.api.entity.SysChatMsg;
import com.kum.domain.entity.Message;
import com.kum.netty.handler.MessageHandler;
import com.kum.utils.ChannelNoticeUtils;
import io.netty.channel.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @version V1.0
 * @Package com.kum.netty.handler
 * @auhter 枯木Kum
 * @date 2021/5/7-3:18 PM
 * <p>...</p>
 */

@Log4j2
@Component
public class SendMessageHandlerImpl implements MessageHandler {

    @Resource
    private RemoteChatMsgService chatMsgService;

    @Override
    public void operation(Channel channel, Message message) {
        SysChatMsg chatMsg = JSON.parseObject(message.getData(), SysChatMsg.class);
        // TODO: 2021/5/9 重写WS握手包实现获取HTTP Session
//        chatMsg.setSendUserId(RequestUtils.getCurrentLoginUserId());

        String chatId = chatMsgService.save(chatMsg);

        log.info("userId {} sent  message to {} ,msgId {}"
                ,chatMsg.getSendUserId(),chatMsg.getAcceptUserId(),chatId);

        // 使用WS通知对方
        ChannelNoticeUtils.sendMessage(chatMsg.getAcceptUserId(),chatMsg);
    }
}
